import XCTest
@testable import YXSilver

final class ChainSerialTasksTests: XCTestCase {
    
    override class func setUp() {
        ChainSerialTasks.shared.chainStarted = true
    }
    
    func testChainSerialTasks_continue() {
        let expection = XCTestExpectation()
        
        ChainSerialTasks.scheduled(key: "task1") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task2") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task3") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task4") { (item) in
            NSLog("\(item.key) runing")
            yx_delay {
                item.fulfill()
                expection.fulfill()
            }
        }

        wait(for: [expection], timeout: 20)
    }
    
    func testChainSerialTasks_reject() {
        let expection = XCTestExpectation()
        
        ChainSerialTasks.scheduled(key: "task1") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task2") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task3") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.reject() }
        }
        
        ChainSerialTasks.scheduled(key: "task4") { (item) in
            NSLog("\(item.key) runing")
            yx_delay {
                item.fulfill()
                expection.fulfill()
            }
        }

        wait(for: [expection], timeout: 20)
    }
    
    func testChainSerialTasks_repeat() {
        
        ChainSerialTasks.scheduled(key: "task1") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task1") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        ChainSerialTasks.scheduled(key: "task2") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.reject() }
        }
        
        ChainSerialTasks.scheduled(key: "task2") { (item) in
            NSLog("\(item.key) runing")
            yx_delay { item.fulfill() }
        }
        
        XCTAssertTrue(ChainSerialTasks.shared.runningTaskKeys.count == 2)
    }
}
